package com.piggy.common.datasource.config;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DefaultDataSourceCreator;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceAutoConfiguration;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.context.scope.refresh.RefreshScopeRefreshedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import javax.sql.DataSource;
import java.util.Map;
import java.util.Set;

@Order(0)
@Configuration
@RequiredArgsConstructor
@ConditionalOnClass(DynamicDataSourceAutoConfiguration.class)
@EnableConfigurationProperties(DynamicDsProperties.class)
@AutoConfigureAfter({DataSourceAutoConfiguration.class, DynamicDataSourceAutoConfiguration.class})
public class DynamicDsConfig implements ApplicationListener<RefreshScopeRefreshedEvent> {
    private final DynamicDsProperties properties;
    private final DataSource dataSource;
    private final DefaultDataSourceCreator creator;

    @Override
    public void onApplicationEvent(RefreshScopeRefreshedEvent event) {
        //获取最新的数据源
        Map<String, DataSourceProperty> datasource = properties.getDatasource();
        //获取原来的数据源
        DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
        //移除当前数据源中不存在的数据源
        Set<String> keys = datasource.keySet();
        //判断是否存在（不存在即删除）
        ds.getDataSources().entrySet().removeIf(next -> !keys.contains(next.getKey()));
        //添加新的数据源
        datasource.forEach((key, value) -> {
            ds.addDataSource(key, creator.createDataSource(value));
        });
    }
}